<!-- views/system/RolePermissions.vue -->
<template>
  <div class="role-permissions-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">角色权限</h1>
        <div class="status-badges">
          <el-tag type="primary" class="total-badge">
            <el-icon><User /></el-icon>
            总角色: {{ stats.totalRoles }}
          </el-tag>
          <el-tag type="success" class="active-badge">
            <el-icon><Check /></el-icon>
            启用角色: {{ stats.activeRoles }}
          </el-tag>
          <el-tag type="warning" class="admin-badge">
            <el-icon><Lock /></el-icon>
            管理员角色: {{ stats.adminRoles }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 新增角色 -->
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="showCreateRoleDialog"
        >
          新增角色
        </el-button>
        
        <!-- 刷新数据 -->
        <el-button 
          :icon="Refresh" 
          @click="loadRoles"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="本月新增角色"
          :value="stats.newRolesThisMonth"
          :icon="UserFilled"
          color="#1890ff"
          :trend="stats.newRoleTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="平均权限数"
          :value="stats.avgPermissions"
          :icon="Lock"
          color="#52c41a"
          :trend="stats.permissionTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="用户分配率"
          :value="stats.userAssignmentRate"
          suffix="%"
          :icon="User"
          color="#fa8c16"
          :trend="stats.assignmentTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="权限更新"
          :value="stats.permissionUpdates"
          :icon="Edit"
          color="#722ed1"
          :trend="stats.updateTrend"
        />
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="角色状态">
          <el-select v-model="queryParams.status" clearable placeholder="全部状态" style="width: 120px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="角色名称">
          <el-input
            v-model="queryParams.name"
            placeholder="输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>角色列表</span>
          <div class="table-actions">
            <el-button-group>
              <el-button :icon="Sort" @click="handleSort('created_at')">
                按创建时间
              </el-button>
              <el-button :icon="Sort" @click="handleSort('user_count')">
                按用户数
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        ref="roleTableRef"
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="handleSortChange"
        class="roles-table"
      >
        <el-table-column type="selection" width="50" />
        
        <!-- 角色基本信息 -->
        <el-table-column prop="name" label="角色名称" min-width="150" fixed>
          <template #default="{ row }">
            <div class="role-basic-cell">
              <span class="role-name">{{ row.name }}</span>
              <!-- 移除不存在的字段引用 -->
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="角色描述" min-width="200" />
        
        <!-- 移除不存在的字段引用 -->
        <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click.stop="editRole(row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click.stop="managePermissions(row)"
            >
              权限
            </el-button>
            <el-dropdown @command="handleMoreAction">
              <el-button size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'copy', row }">
                    <el-icon><CopyDocument /></el-icon>复制角色
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', row }" divided>
                    <el-icon><Delete /></el-icon>删除角色
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="table-pagination"
      />
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="roleForm.id ? '编辑角色' : '新增角色'"
      width="600px"
    >
      <el-form 
        :model="roleForm" 
        ref="roleFormRef" 
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input 
            v-model="roleForm.name" 
            placeholder="请输入角色名称"
          />
        </el-form-item>
        
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="saveRole"
          :loading="saving"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限管理抽屉 -->
    <el-drawer
      v-model="permissionDrawerVisible"
      title="权限管理"
      direction="rtl"
      size="600px"
    >
      <div class="permission-management" v-if="currentRole">
        <div class="role-info">
          <h3>{{ currentRole.name }} - 权限配置</h3>
          <p>{{ currentRole.description }}</p>
        </div>
        
        <el-tabs v-model="activePermissionTab">
          <el-tab-pane label="菜单权限" name="menu">
            <div class="permission-tree">
              <el-tree
                ref="menuTreeRef"
                :data="menuPermissions"
                show-checkbox
                node-key="id"
                :default-checked-keys="currentRole.menuPermissions || []"
                :props="treeProps"
                @check="handleMenuCheck"
              />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="操作权限" name="action">
            <div class="permission-list">
              <el-checkbox-group 
                :model-value="currentRole.actionPermissions || []"
                @update:model-value="handleActionPermissionChange"
              >
                <el-row :gutter="20">
                  <el-col 
                    v-for="permission in actionPermissions" 
                    :key="permission.id"
                    :span="12"
                  >
                    <el-checkbox 
                      :label="permission.id"
                      :disabled="permission.isSystem"
                    >
                      {{ permission.name }}
                      <el-tag 
                        v-if="permission.isSystem" 
                        size="small" 
                        type="danger"
                      >
                        系统
                      </el-tag>
                    </el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="数据权限" name="data">
            <div class="data-permission-config">
              <el-form :model="dataPermissionConfig" label-width="120px">
                <el-form-item label="数据范围">
                  <el-select 
                    v-model="dataPermissionConfig.scope" 
                    placeholder="请选择数据范围"
                    style="width: 100%"
                  >
                    <el-option label="全部数据" value="all" />
                    <el-option label="本部门数据" value="department" />
                    <el-option label="本人数据" value="self" />
                    <el-option label="自定义数据" value="custom" />
                  </el-select>
                </el-form-item>
                
                <el-form-item 
                  v-if="dataPermissionConfig.scope === 'custom'" 
                  label="自定义部门"
                >
                  <el-tree-select
                    v-model="dataPermissionConfig.departments"
                    :data="departments"
                    multiple
                    show-checkbox
                    check-strictly
                    node-key="id"
                    :props="treeProps"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <el-button @click="permissionDrawerVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="savePermissions"
          :loading="savingPermissions"
        >
          保存权限
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { ref, reactive, onMounted } from '@vue/runtime-core'
// @ts-ignore
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, Check, Lock, Plus, Refresh, Search, Sort, View, Edit, More, Delete, Unlock,
  ArrowDown, CopyDocument, UserFilled
} from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/appStore'
import MetricCard from '@/views/dashboard/components/MetricCard.vue'
import { systemAPI } from '@/api/system'

// Store
const appStore = useAppStore()

// 类型定义
interface RoleItem {
  id: number
  name: string
  description: string
  createdAt: string
  updatedAt: string
}

// 响应式数据
const roleTableRef = ref()
const loading = ref(false)
const saving = ref(false)

const selectedRoles = ref<any[]>([])
const tableData = ref<RoleItem[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 对话框相关
const roleDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const permissionDrawerVisible = ref(false)
const savingPermissions = ref(false)

// 表单数据
const roleForm = ref({
  id: 0,
  name: '',
  description: ''
})

const roleFormRules = ref({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
})

// 角色详情和编辑数据
const detailRole = ref<RoleItem>({
  id: 0,
  name: '',
  description: '',
  createdAt: '',
  updatedAt: ''
})

const editingRole = ref({
  id: 0,
  name: '',
  description: ''
})

const currentRole = ref<RoleItem | null>(null)

// 统计数据
const stats = reactive({
  totalRoles: 0,
  activeRoles: 0,
  adminRoles: 0,
  newRolesThisMonth: 0,
  avgPermissions: 0,
  userAssignmentRate: 0,
  permissionUpdates: 0,
  newRoleTrend: 0,
  permissionTrend: 0,
  assignmentTrend: 0,
  updateTrend: 0
})

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 20,
  name: '',
  status: ''
})

// 权限管理相关数据
const activePermissionTab = ref('menu')

// 树形组件属性
const treeProps = {
  label: 'name',
  children: 'children'
}

// 菜单权限数据
const menuPermissions = ref([
  {
    id: 'dashboard',
    name: '仪表板',
    children: [
      { id: 'dashboard_overview', name: '概览' },
      { id: 'dashboard_analytics', name: '分析' }
    ]
  },
  {
    id: 'reconciliation',
    name: '对账管理',
    children: [
      { id: 'reconciliation_smart', name: '智能对账' },
      { id: 'reconciliation_manual', name: '手工对账' },
      { id: 'reconciliation_results', name: '对账结果' }
    ]
  },
  {
    id: 'reports',
    name: '报告中心',
    children: [
      { id: 'reports_reconciliation', name: '对账报告' },
      { id: 'reports_statistics', name: '统计分析' },
      { id: 'reports_habits', name: '客户习惯' }
    ]
  },
  {
    id: 'system',
    name: '系统管理',
    children: [
      { id: 'system_users', name: '用户管理' },
      { id: 'system_roles', name: '角色权限' },
      { id: 'system_logs', name: '操作日志' },
      { id: 'system_settings', name: '系统设置' }
    ]
  }
])

// 操作权限数据
const actionPermissions = ref([
  { id: 'user_create', name: '创建用户', isSystem: false },
  { id: 'user_edit', name: '编辑用户', isSystem: false },
  { id: 'user_delete', name: '删除用户', isSystem: false },
  { id: 'role_create', name: '创建角色', isSystem: false },
  { id: 'role_edit', name: '编辑角色', isSystem: false },
  { id: 'role_delete', name: '删除角色', isSystem: false },
  { id: 'system_backup', name: '系统备份', isSystem: true },
  { id: 'system_restore', name: '系统恢复', isSystem: true }
])

// 数据权限配置
const dataPermissionConfig = ref({
  scope: 'all',
  departments: [] as string[]
})

// 部门数据
const departments = ref([
  { id: 'dept_1', name: '销售部' },
  { id: 'dept_2', name: '采购部' },
  { id: 'dept_3', name: '财务部' },
  { id: 'dept_4', name: '运营部' }
])

// 权限选项
const permissionOptions = [
  { label: '用户管理', value: 'user_management' },
  { label: '角色管理', value: 'role_management' },
  { label: '系统设置', value: 'system_settings' },
  { label: '对账管理', value: 'reconciliation_management' },
  { label: '报告查看', value: 'report_view' },
  { label: '日志查看', value: 'log_view' }
]

// 方法
const loadRoles = async () => {
  loading.value = true
  try {
    const response = await systemAPI.getRoles()
    console.log('API响应数据:', response)
    if (response.success && response.data) {
      tableData.value = response.data.list || []
      pagination.total = response.data.pagination?.total || 0
    }
  } catch (error: any) {
    ElMessage.error('加载角色数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  // 这里可以调用获取统计信息的API
  // 暂时使用模拟数据
  stats.totalRoles = 8
  stats.activeRoles = 6
  stats.adminRoles = 1
  stats.newRolesThisMonth = 2
  stats.avgPermissions = 12
  stats.userAssignmentRate = 95
  stats.permissionUpdates = 24
  stats.newRoleTrend = 5
  stats.permissionTrend = 2.3
  stats.assignmentTrend = -1.2
  stats.updateTrend = 0.8
}

const handleSearch = () => {
  pagination.page = 1
  loadRoles()
}

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    limit: 20,
    name: '',
    status: ''
  })
  loadRoles()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRoles.value = selection
}

const handleRowClick = (row: any) => {
  // 可以显示快速详情
  console.log('点击角色:', row)
}

const handleSort = (field: string) => {
  // 排序逻辑可以根据需要实现
  loadRoles()
}

const handleSortChange = ({ prop, order }: any) => {
  // 排序逻辑可以根据需要实现
  loadRoles()
}

const handleSizeChange = (val: number) => {
  pagination.limit = val
  pagination.page = 1
  loadRoles()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  loadRoles()
}

const showRoleDetail = async (role: RoleItem) => {
  try {
    const response = await systemAPI.getRole(role.id.toString())
    if (response.success && response.data) {
      detailRole.value = response.data
      detailDialogVisible.value = true
    }
  } catch (error: any) {
    ElMessage.error('获取角色详情失败: ' + (error.message || '未知错误'))
  }
}

const editRole = async (role: RoleItem) => {
  try {
    const response = await systemAPI.getRole(role.id.toString())
    if (response.success && response.data) {
      roleForm.value = { ...response.data }
      roleDialogVisible.value = true
    }
  } catch (error: any) {
    ElMessage.error('获取角色信息失败: ' + (error.message || '未知错误'))
  }
}

const deleteRole = async (role: RoleItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 "${role.name}" 吗？`, '删除角色', {
      type: 'warning'
    })
    
    const response = await systemAPI.deleteRole(role.id.toString())
    if (response.success) {
      ElMessage.success('删除成功')
      loadRoles()
    } else {
      ElMessage.error('删除失败: ' + (response.message || '未知错误'))
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

const handleMoreAction = (command: { action: string; row: RoleItem }) => {
  const { action, row } = command
  switch (action) {
    case 'copy':
      copyRole(row)
      break
    case 'delete':
      deleteRole(row)
      break
  }
}

const copyRole = async (role: RoleItem) => {
  try {
    // 实现复制角色的逻辑
    ElMessage.info(`复制角色 ${role.name}`)
  } catch (error: any) {
    ElMessage.error('复制角色失败: ' + (error.message || '未知错误'))
  }
}

const showCreateRoleDialog = () => {
  // 重置表单
  roleForm.value = {
    id: 0,
    name: '',
    description: ''
  }
  roleDialogVisible.value = true
}

const saveRole = async () => {
  try {
    saving.value = true
    
    if (roleForm.value.id) {
      // 更新角色
      await systemAPI.updateRole(roleForm.value.id.toString(), {
        name: roleForm.value.name,
        description: roleForm.value.description
      })
      ElMessage.success('角色更新成功')
    } else {
      // 创建角色
      await systemAPI.createRole({
        name: roleForm.value.name,
        description: roleForm.value.description
      })
      ElMessage.success('角色创建成功')
    }
    
    roleDialogVisible.value = false
    loadRoles()
  } catch (error: any) {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

// 权限管理相关方法
const managePermissions = (role: RoleItem) => {
  currentRole.value = { ...role }
  permissionDrawerVisible.value = true
}

const handleMenuCheck = (data: any, checkedInfo: any) => {
  if (currentRole.value) {
    // 更新菜单权限
    console.log('菜单权限更新:', data, checkedInfo)
  }
}

const handleActionPermissionChange = (values: string[]) => {
  if (currentRole.value) {
    // 更新操作权限
    console.log('操作权限更新:', values)
    // 这里可以更新currentRole.value.actionPermissions
  }
}

const savePermissions = async () => {
  if (!currentRole.value) return
  
  try {
    savingPermissions.value = true
    // 这里应该调用API保存权限设置
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('权限保存成功')
    permissionDrawerVisible.value = false
    loadRoles()
  } catch (error: any) {
    ElMessage.error('保存权限失败: ' + (error.message || '未知错误'))
  } finally {
    savingPermissions.value = false
  }
}

// 工具函数
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  appStore.setPageTitle('角色权限')
  loadRoles()
  loadStats()
})
</script>

<style scoped lang="scss">
.role-permissions-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .header-left {
      .page-title {
        margin: 0 0 12px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2d3d;
      }
      
      .status-badges {
        display: flex;
        gap: 12px;
        
        .el-tag {
          display: flex;
          align-items: center;
          gap: 4px;
          font-weight: 500;
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-row {
    margin-bottom: 20px;
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .role-basic-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .role-name {
        font-weight: 500;
      }
      
      .default-tag,
      .admin-tag {
        margin-left: 8px;
      }
    }
    
    .table-pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
  
  .permission-management {
    padding: 20px;
    
    .role-info {
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;
      
      h3 {
        margin: 0 0 8px 0;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
      }
    }
    
    .permission-tree,
    .permission-list,
    .data-permission-config {
      margin-top: 20px;
    }
    
    .permission-list {
      .el-checkbox {
        margin-bottom: 12px;
        display: flex;
        align-items: center;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .role-permissions-management {
    padding: 12px;
    
    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }
    
    .stats-row {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>